image: node:18-alpine3.16

variables:
  TEXTBOOK_FILE_NAME: devops-textbook.docx
  TEXTBOOK_OUTPUT_DIRECTORY: "./textbook"
  DIRECTORY_WITH_MARKDOWN_FILES: "./website/docs"

stages:
  - test
  - build
  - deploy

test:
  tags:
    - iu5edu
  stage: test
  rules:
    - if: $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH
  script:
    - cd website
    - yarn install
    - yarn build

site:
  tags:
    - iu5edu
  stage: build
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      changes:
        - website/**/*
  script:
    - cd website
    - yarn install
    - yarn build
    - mv ./build ../pages
  artifacts:
    paths:
      - pages

presentations:
  tags:
    - iu5edu
  stage: build
  variables:
    PRESENTATIONS_SRC_DIR: "${CI_PROJECT_DIR}/src/lectures"
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      changes:
        - src/lectures/**/*
        - website/**/*
  script:
    - npm install -g @marp-team/marp-cli
    - cd ${PRESENTATIONS_SRC_DIR}
    - marp --allow-local-files -I . -o ./build
    - apk add --no-cache bash
    - bash copy-images.sh
    - cd ${CI_PROJECT_DIR}
    - mv ${PRESENTATIONS_SRC_DIR}/build ./presentations
  artifacts:
    paths:
      - presentations

docx:
  image: registry.gitlab.com/iu5edu/docker/docusaurus-docx-builder
  tags:
    - iu5edu
  stage: build
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      changes:
        - website/**/*
  script:
    - echo GE_JOB_ID=$CI_JOB_ID >> build_docx.env
    - export COMBINED_DOCX_NAME=$TEXTBOOK_FILE_NAME
    - export OUTPUT_DIRECTORY=${TEXTBOOK_OUTPUT_DIRECTORY}
    - export DIRECTORY_WITH_MARKDOWN_FILES=${DIRECTORY_WITH_MARKDOWN_FILES}
    - python3 ./pandoc-builder.py
  artifacts:
    paths:
      - ${TEXTBOOK_OUTPUT_DIRECTORY}/${TEXTBOOK_FILE_NAME}
    reports:
      dotenv: build_docx.env # Use artifacts:reports:dotenv to expose the variables to other jobs

deploy:
  tags:
    - iu5edu-prod
  stage: deploy
  needs:
    - job: site
      artifacts: true
    - job: presentations
      artifacts: true
    - job: docx
      artifacts: true
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      changes:
        - website/**/*
  variables:
    DEPLOY_DIR: "/home/gitlab-runner/www/devops_wiki"
  environment:
    name: production
  script:
    - mv ./pages ./public
    - mv ./${TEXTBOOK_OUTPUT_DIRECTORY} ./public/documents
    - mv ./presentations ./public/presentations
    - rm -rf ${DEPLOY_DIR}/*
    - cp -r ./public/. ${DEPLOY_DIR}/.
  after_script:
    - rm -r ${CI_PROJECT_DIR}
